import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:wayofdressing/contraints.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import 'package:wayofdressing/dio/configureDio.dart';
import 'package:wayofdressing/dio/PostDio.dart';
import 'package:wayofdressing/all_information/user_information.dart';
import 'package:wayofdressing/good_method/show_dialog.dart';

class PublishScreen extends StatefulWidget {
  @override
  State<PublishScreen> createState() => _PublishScreenState();
}

class _PublishScreenState extends State<PublishScreen> {
  File? _image;
  List<Widget> photosList = [];
  late Widget addImage;
  TextEditingController titleEditingController = TextEditingController();
  TextEditingController contentEditingController = TextEditingController();

  Future getImage() async {
    final ImagePicker picker = ImagePicker();
    final XFile? image = await picker.pickImage(source: ImageSource.gallery);

    if (image != null) {
      setState(() {
        _image = File(image.path);
        photosList.removeLast();
        photosList.add(AspectRatio(
          aspectRatio: 1,
          child: ClipRRect(
            borderRadius: BorderRadius.circular(10),
            child: Image.file(
              _image!,
            ),
          ),
        ));
        photosList.add(SizedBox(
          width: 8,
        ));
        photosList.add(addImage);
      });
    }
  }

  Future<void> uploadPost() async {
    if (titleEditingController.text == '' ||
        contentEditingController.text == '') {
      ShowDialog.showErrorAndDetail(context, '输入不能为空!');
      return;
    }
    isPost=true;
    Map<String, dynamic> postDTO = {
      'title': titleEditingController.text,
      'content': contentEditingController.text
    };
    Response response = await addNewPost(
        userId: userId, postDTO: postDTO, dio: dio, imagePath: _image?.path);
    if (response.data['success'] == true) {
      ShowDialog.showCorrect(context);
    } else {
      isPost=false;
      ShowDialog.showErrorAndDetail(context, '发布失败');
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    addImage = GestureDetector(
        onTap: () {
          getImage();
        },
        child: AspectRatio(
          aspectRatio: 1,
          child: Container(
            decoration: BoxDecoration(
                color: Colors.grey[200],
                borderRadius: BorderRadius.circular(15)),
            child: Icon(
              Icons.add_rounded,
              color: Colors.grey,
            ),
          ),
        ));
    photosList = [addImage];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfffffaf0),
      appBar: AppBar(
        backgroundColor: Color(0xfffffaf0),
        elevation: 0,
        toolbarHeight: 80,
        leadingWidth: 100,
        centerTitle: true,
        leading: Row(
          children: [
            SizedBox(
              width: 10,
            ),
            GestureDetector(
              onTap: () {
                Navigator.pop(context);
              },
              child: Transform.scale(
                scaleX: -1,
                child: Icon(
                  Icons.play_arrow_rounded,
                  size: kAppBarButtonSize,
                  color: Colors.black.withOpacity(0.5),
                ),
              ),
            ),
          ],
        ),
      ),
      body: Container(
        margin: EdgeInsets.symmetric(horizontal: 15),
        child: Column(
          children: [
            Expanded(
              flex: 2,
              child: ListView.builder(
                  scrollDirection: Axis.horizontal,
                  itemCount: photosList.length,
                  itemBuilder: (context, index) => photosList[index]),
            ),
            Expanded(
              flex: 2,
              child: TextField(
                controller: titleEditingController,
                decoration: InputDecoration(
                  labelText: '填写标题',
                  labelStyle: TextStyle(fontSize: 20, color: Colors.grey),
                  enabledBorder: UnderlineInputBorder(
                    borderSide: BorderSide(color: Colors.grey), // 默认状态颜色
                  ),
                  focusedBorder: UnderlineInputBorder(
                    borderSide: BorderSide(color: Colors.grey), // 聚焦状态颜色
                  ),
                ),
              ),
            ),
            Expanded(
              flex: 6,
              child: TextField(
                maxLines: null,
                textAlignVertical: TextAlignVertical.top,
                controller: contentEditingController,
                decoration: InputDecoration(
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.only(bottom: 100.0),
                  labelText: '填写内容',
                  labelStyle: TextStyle(fontSize: 18, color: Colors.grey),
                  enabledBorder: UnderlineInputBorder(
                    borderSide: BorderSide(color: Colors.grey), // 默认状态颜色
                  ),
                  focusedBorder: UnderlineInputBorder(
                    borderSide: BorderSide(color: Colors.grey), // 聚焦状态颜色
                  ),
                ),
              ),
            ),
            Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [
                        Icon(Icons.location_on_outlined),
                        SizedBox(
                          width: 5,
                        ),
                        Text('标记地点'),
                      ],
                    ),
                    Text('标记地点让更多人看到'),
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [
                        Icon(Icons.lock_open_rounded),
                        SizedBox(
                          width: 5,
                        ),
                        Text('公开可见'),
                      ],
                    ),
                    Switch(value: true, onChanged: (value) {}),
                  ],
                ),
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Column(
                  children: [
                    CircleAvatar(
                      radius: 18,
                      backgroundColor: Colors.grey[300],
                      child: Icon(
                        Icons.drafts_outlined,
                        size: 24,
                        color: Colors.black,
                      ),
                    ),
                    Text(
                      '存草稿',
                      style: TextStyle(fontSize: 12),
                    ),
                  ],
                ),
                SizedBox(
                  width: 18,
                ),
                Column(
                  children: [
                    CircleAvatar(
                      radius: 18,
                      backgroundColor: Colors.grey[300],
                      child: Icon(
                        Icons.visibility_outlined,
                        size: 24,
                        color: Colors.black,
                      ),
                    ),
                    Text(
                      '预览',
                      style: TextStyle(fontSize: 12),
                    ),
                  ],
                ),
                SizedBox(
                  width: 18,
                ),
                Expanded(
                    child: Container(
                  height: 42,
                  child: TextButton(
                    style: ButtonStyle(
                        shape: MaterialStateProperty.all(RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(25))),
                        backgroundColor: MaterialStateProperty.all(Colors.red)),
                    child: Text(
                      '发布笔记',
                      style: TextStyle(color: Colors.white, fontSize: 16),
                    ),
                    onPressed: () {
                      if(!isPost){
                        uploadPost();
                      }
                    },
                  ),
                )),
              ],
            ),
            SizedBox(
              height: 20,
            )
          ],
        ),
      ),
    );
  }
}
